import 'package:base_lib/common/base/base_theme_state.dart';
import 'package:base_lib/dictionary/dictionary_provider.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/theme/theme_global.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../dictionary/entity/sickness_group_entity.dart' as SicknessGroupBean;
import '../dictionary/entity/sickness_item_entity.dart' as SicknessItemBean;

class SicknessInfoWidget extends StatefulWidget {
  final TextStyle textStyle;
  final bool isFemale;
  final SicknessResult defValue;
  final Function(SicknessResult) callback;

  SicknessInfoWidget(
    this.callback, {
    this.defValue,
    this.isFemale = false,
    this.textStyle = const TextStyle(fontSize: 15, color: Colors.black),
  });

  @override
  State<StatefulWidget> createState() {
    return _SicknessInfoWidgetState();
  }
}

class _SicknessInfoWidgetState extends BaseThemeState<SicknessInfoWidget> {
  @override
  void initState() {
    super.initState();
    getSicknessGroup();
    getSicknessInfo();
  }

  List<SicknessGroupBean.Data> groupList = [];

  void getSicknessGroup() async {
    groupList.clear();
    var result = await DictionaryProvider.getSicknessGroup();
    if (result.isSuccess) {
      groupList.addAll(
          SicknessGroupBean.SicknessGroupEntity.fromJson(result.data).data);
    }
    doRefresh();
  }

  void getSicknessInfo() async {
    List<SicknessItemBean.Data> sicknessList = [];
    var result = await DictionaryProvider.getSicknessItem();
    if (result.isSuccess) {
      sicknessList.addAll(
          SicknessItemBean.SicknessItemEntity.fromJson(result.data).data);
    }

    allergyList
      ..addAll(sicknessList.where((e) => e.parentDictCode == 'ALLERGY'));

    pastMedicalList
      ..addAll(sicknessList.where((e) => e.parentDictCode == 'ILLNESS'));

    if (widget.defValue != null) {
      var defAllergyList = widget.defValue.allergyDetail
              .split(',')
              .map((e) =>
                  SicknessItemBean.Data(parentDictCode: 'ALLERGY', dictName: e))
              .toList() ??
          [];

      allergyList.removeWhere((element) {
        return (defAllergyList
                .where((defE) => defE.dictName == element.dictName)
                ?.isNotEmpty ??
            false);
      });

      allergyList.addAll(defAllergyList);
      checkedList.addAll(defAllergyList);

      var defSicknessList = widget.defValue.sicknessDetail
              .split(',')
              .map((e) =>
                  SicknessItemBean.Data(parentDictCode: 'ILLNESS', dictName: e))
              .toList() ??
          [];

      pastMedicalList.removeWhere((element) {
        return (defSicknessList
                .where((defE) => defE.dictName == element.dictName)
                ?.isNotEmpty ??
            false);
      });

      pastMedicalList.addAll(defSicknessList);
      checkedList.addAll(defSicknessList);

      this.historyOfAllergy = widget.defValue.historyOfAllergy;
      this.historyOfSickness = widget.defValue.historyOfSickness;
      this.liver = widget.defValue.liver;
      this.renal = widget.defValue.renal;
      this.pregnancy = widget.defValue.pregnancy;
    }

    allergyList
      ..add(SicknessItemBean.Data(parentDictCode: 'ALLERGY', dictName: '+'));

    pastMedicalList
      ..add(SicknessItemBean.Data(parentDictCode: 'ILLNESS', dictName: '+'));

    doRefresh();
  }

  doRefresh() {
    widget.callback(getResult());
    setState(() {});
  }

  @override
  Widget buildChild(BuildContext context, MTheme theme) {
    return groupList.isEmpty
        ? buildLoadingIndicator()
        : Column(
            children: [
              1.gapV(Colors.grey[350]),
              //过敏史
              _buildAllergyHistory(theme),
              1.gapV(Colors.grey[350]),
              //既往病史
              _buildPastMedicalHistory(theme),
              1.gapV(Colors.grey[350]),
              //肝功能
              _buildLiverFunction(theme),
              1.gapV(Colors.grey[350]),
              //肾功能
              _buildRenalFunction(theme),
              1.gapV(Colors.grey[350]),
              //妊娠期
              widget.isFemale ? _buildPregnancyPeriod(theme) : SizedBox(),
              widget.isFemale ? 1.gapV(Colors.grey[350]) : SizedBox(),
            ],
          );
  }

  ///选中的item
  List<SicknessItemBean.Data> checkedList = [];

  ///过敏
  String historyOfAllergy = '无';
  String allergyDetail = '';
  List<SicknessItemBean.Data> allergyList = [];

  //过敏史
  _buildAllergyHistory(MTheme theme) {
    var des = '过敏史';
    return Container(
      child: Column(
        children: [
          Row(
            children: [
              10.hGapDp,
              Text(
                des,
                style: widget.textStyle,
              ),
              Spacer(),
              Radio(
                  value: '有',
                  groupValue: historyOfAllergy,
                  onChanged: (v) {
                    historyOfAllergy = v;
                    doRefresh();
                  }),
              Text('有'),
              20.hGapDp,
              Radio(
                  value: '无',
                  groupValue: historyOfAllergy,
                  onChanged: (b) {
                    historyOfAllergy = b;
                    doRefresh();
                  }),
              Text('无'),
              10.hGapDp,
            ],
          ),
          historyOfAllergy == '有'
              ? _buildItems(allergyList, theme)
              : SizedBox(),
        ],
      ),
    );
  }

  ///既往病史
  String historyOfSickness = '无';
  String sicknessDetail = '';
  List<SicknessItemBean.Data> pastMedicalList = [];

  //既往病史
  _buildPastMedicalHistory(MTheme theme) {
    var des = '既往病史';
    return Container(
      child: Column(
        children: [
          Row(
            children: [
              10.hGapDp,
              Text(
                des,
                style: widget.textStyle,
              ),
              Spacer(),
              Radio(
                  value: '有',
                  groupValue: historyOfSickness,
                  onChanged: (b) {
                    historyOfSickness = b;
                    doRefresh();
                  }),
              Text('有'),
              20.hGapDp,
              Radio(
                  value: '无',
                  groupValue: historyOfSickness,
                  onChanged: (b) {
                    historyOfSickness = b;
                    doRefresh();
                  }),
              Text('无'),
              10.hGapDp,
            ],
          ),
          historyOfSickness == '有'
              ? _buildItems(pastMedicalList, theme)
              : SizedBox(),
        ],
      ),
    );
  }

  _buildItems(List<SicknessItemBean.Data> list, MTheme theme) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
          color: theme.themeColor.themeBgColor,
          borderRadius: BorderRadius.circular(5)),
      padding: EdgeInsets.all(10),
      child: Wrap(
        alignment: WrapAlignment.start,
        spacing: 10,
        runSpacing: 10,
        children: list.map((e) {
          var isChecked = checkedList.contains(e);
          Widget w;
          if (e.dictName == '+') {
            w = Icon(Icons.add, size: 15);
          } else {
            w = Text(
              e.dictName,
              style: TextStyle(color: isChecked ? Colors.white : Colors.black),
            );
          }

          return GestureDetector(
            onTap: () {
              if (e.dictName == '+') {
                showAddDialog(e.parentDictCode == 'ALLERGY', e.parentDictCode);
              } else {
                checkedList.contains(e)
                    ? checkedList.remove(e)
                    : checkedList.add(e);
                doRefresh();
              }
            },
            child: Container(
              decoration: BoxDecoration(
                  color: isChecked ? theme.themeColor.themeColor : Colors.white,
                  border: Border.all(color: Colors.grey[350]),
                  borderRadius: BorderRadius.circular(10)),
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
              child: w,
            ),
          );
        }).toList(),
      ),
    );
  }

  void showAddDialog(bool isAllergyHistory, String code) {
    String tag = '';

    var height = 230.0;
    var oneItemHeight = height / 3 - 5;
    CustomDialog.customDialog(context,
        child: Container(
          width: ScreenAdapter.screenWidthDp * 0.82,
          height: height,
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(20)),
          child: Column(
            children: [
              Expanded(
                child: Row(
                  children: [
                    Spacer(),
                    Text(
                      '添加标签',
                      style: TextStyle(fontSize: 16, color: Colors.black),
                    ),
                    Expanded(
                      child: IconButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        icon: Icon(Icons.close),
                      ),
                    )
                  ],
                ),
              ),
              1.gapVdp(Colors.grey[200]),
              Expanded(
                child: Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey[350]),
                      borderRadius: BorderRadius.circular(10)),
                  margin: EdgeInsets.all(10),
                  padding: EdgeInsets.symmetric(horizontal: 10),
                  child: TextField(
                    style: TextStyle(textBaseline: TextBaseline.alphabetic),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: '请输入标签',
                    ),
                    onChanged: (str) {
                      tag = str;
                    },
                  ),
                ),
              ),
              1.gapVdp(Colors.grey[200]),
              Expanded(
                child: Row(
                  children: [
                    Expanded(
                      child: FlatButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        child: Text(
                          '取消',
                          style: TextStyle(color: Colors.grey),
                        ),
                      ),
                    ),
                    Container(
                      width: 1,
                      height: oneItemHeight,
                      color: Colors.grey[200],
                    ),
                    Expanded(
                      child: FlatButton(
                        onPressed: () {
                          SicknessItemBean.Data data;
                          if (isAllergyHistory) {
                            data = SicknessItemBean.Data(
                              dictCode: "${code}_${allergyList.length + 1}",
                              parentDictCode: code,
                              dictName: tag,
                            );
                            allergyList.insert(allergyList.length, data);
                          } else {
                            data = SicknessItemBean.Data(
                              dictCode: "${code}_${pastMedicalList.length + 1}",
                              parentDictCode: code,
                              dictName: tag,
                            );
                            pastMedicalList.insert(
                                pastMedicalList.length, data);
                          }
                          checkedList.add(data);
                          doRefresh();
                          Navigator.pop(context);
                        },
                        child: Text(
                          '添加',
                          style: TextStyle(
                              color: ThemeGlobal
                                  .instance.themeData.themeColor.themeColor),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ));
  }

  ///肝
  String liver = '正常';

  //肝功能
  _buildLiverFunction(MTheme theme) {
    var des = '肝功能';
    return Row(
      children: [
        10.hGapDp,
        Text(
          des,
          style: widget.textStyle,
        ),
        Spacer(),
        Radio(
            value: '正常',
            groupValue: liver,
            onChanged: (b) {
              liver = b;
              doRefresh();
            }),
        Text('正常'),
        20.hGapDp,
        Radio(
            value: '异常',
            groupValue: liver,
            onChanged: (b) {
              liver = b;
              doRefresh();
            }),
        Text('异常'),
        10.hGapDp,
      ],
    );
  }

  ///肾
  String renal = '正常';

  //肾功能
  _buildRenalFunction(MTheme theme) {
    var des = '肾功能';
    return Row(
      children: [
        10.hGapDp,
        Text(
          des,
          style: widget.textStyle,
        ),
        Spacer(),
        Radio(
            value: '正常',
            groupValue: renal,
            onChanged: (b) {
              renal = b;
              doRefresh();
            }),
        Text('正常'),
        20.hGapDp,
        Radio(
            value: '异常',
            groupValue: renal,
            onChanged: (b) {
              renal = b;
              doRefresh();
            }),
        Text('异常'),
        10.hGapDp,
      ],
    );
  }

  ///妊娠哺乳
  String pregnancy = '否';

  //妊娠哺乳
  _buildPregnancyPeriod(MTheme theme) {
    var des = '妊娠哺乳';
    return Row(
      children: [
        10.hGapDp,
        Text(
          des,
          style: widget.textStyle,
        ),
        Spacer(),
        Radio(
            value: '是',
            groupValue: pregnancy,
            onChanged: (v) {
              pregnancy = v;
              doRefresh();
            }),
        Text('是'),
        20.hGapDp,
        Radio(
            value: '否',
            groupValue: pregnancy,
            onChanged: (b) {
              pregnancy = b;
              doRefresh();
            }),
        Text('否'),
        10.hGapDp,
      ],
    );
  }

  SicknessResult getResult() {
    allergyDetail = '';
    sicknessDetail = '';
    checkedList.forEach((element) {
      if (element.parentDictCode == 'ALLERGY') {
        var pre = this.allergyDetail.isEmpty ? '' : ',';
        this.allergyDetail += '$pre${element.dictName}';
      } else {
        var pre = this.sicknessDetail.isEmpty ? '' : ',';
        this.sicknessDetail += '$pre${element.dictName}';
      }
    });

    return SicknessResult(
        this.historyOfAllergy,
        this.allergyDetail,
        this.historyOfSickness,
        this.sicknessDetail,
        this.liver,
        this.renal,
        this.pregnancy);
  }
}

class SicknessResult {
  ///过敏
  String historyOfAllergy = '无';
  String allergyDetail = '';

  ///既往病史
  String historyOfSickness = '无';
  String sicknessDetail = '';

  ///肝
  String liver = '正常';

  ///肾
  String renal = '正常';

  ///妊娠哺乳
  String pregnancy = '否';

  SicknessResult(
      this.historyOfAllergy,
      this.allergyDetail,
      this.historyOfSickness,
      this.sicknessDetail,
      this.liver,
      this.renal,
      this.pregnancy);

  @override
  String toString() {
    return 'SicknessResult{historyOfAllergy: $historyOfAllergy, allergyDetail: $allergyDetail, historyOfSickness: $historyOfSickness, sicknessDetail: $sicknessDetail, liver: $liver, renal: $renal, pregnancy: $pregnancy}';
  }
}
